package job.mihayou;

import java.util.*;

/**
 * Author: Zhang Dongwei
 * Date: 2023/8/12 16:36
 */
public class mhy3 {

    static int n;
    static List<List<Integer>> graph = new ArrayList<>();
    static int[] v;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        v= new int[n+1];
        for (int i = 0; i <= n; i++) graph.add(new LinkedList<>());

        for (int i = 1; i <= n; i++) {
            v[i] = sc.nextInt();
        }

        for (int i = 0; i < n - 1; i++) {
            int u = sc.nextInt();
            int v = sc.nextInt();
            graph.get(u).add(v);
            graph.get(v).add(u);
        }

        res = dfs_getvals(1, -1, 1); //计算原本树上的所有价值
        val = res; // 原本的总的不完美值。
        dfs(1, -1, 1);
        System.out.println(res);
    }

    static int dfs_getvals(int node, int pre, int deph) {
        int cur = v[node] * deph;

        for (int next : graph.get(node)) {
            if (next != pre) {
                cur += dfs_getvals(next, node, deph + 1);
            }
        }
        return cur;
    }

    static int res = 0;
    static int val;
    // 枚举需要修改的子树，将子树挪到根节点下面，减去相应的权值即可。
    static int dfs(int node, int pre, int depth) {
        int cur = v[node];
        for (int next : graph.get(node)) {
            if (next != pre) {
                cur += dfs(next, node, depth+ 1);
            }
        }

        res = Math.min(res, val - cur * (depth - 2));
        return cur;
    }
}
